<?php

namespace Cola\Ext\Log;

use Cola\Cola;
use RuntimeException;

/**
 * Class Factory
 *
 * @package Cola\Ext\Log
 *
 * @method static void log($event, $log, $context = array())
 * @method static void emergency($log, $context = array())
 * @method static void alert($log, $context = array())
 * @method static void critical($log, $context = array())
 * @method static void error($log, $context = array())
 * @method static void warning($log, $context = array())
 * @method static void notice($log, $context = array())
 * @method static void info($log, $context = array())
 * @method static void debug($log, $context = array())
 * @method static void format($log, $context = array())
 * @method static void setChannel($channel)
 * @method static void write($text)
 */
class Factory
{
    protected static $reg_name = '_cola_logger';

    /**
     * @return \Cola\Ext\Log\Base
     *
     */
    public static function buildLogger() {
        $log_config = Cola::getConfig('cola_log', [
            'driver' => 'file'
        ]);

        $driver = $log_config['driver'] ?? 'file';

        if(strpos($driver, '\\') === false) {
            $driver = ucfirst($driver);
            $driver = "\\Cola\\Ext\\Log\\{$driver}";
        }

        return new $driver($log_config);
    }

    protected static function getLogger() {

        if( $logger = Cola::getReg(static::$reg_name) ) {
            return $logger;
        }

        $logger = static::buildLogger();

        register_shutdown_function([$logger, 'shutdown']);

        Cola::setReg(static::$reg_name, $logger);

        return $logger;
    }

    public static function __callStatic($name, $arguments) {
        $instance = static::getLogger();

        if (! $instance) {
            throw new RuntimeException('get logger fail');
        }

        $instance->$name(...$arguments);
    }


}
